# -*- coding: UTF-8 -*-
import os
import re
import time
import paramiko


class ConnectSSH(object):
    def __init__(self, ip, _username, _password, timeout=30):
        self.ip = ip
        self.username = _username
        self.password = _password
        self.timeout = timeout
        self.client = None
        self.try_times = 3  # 链接失败的重试次数

    def connect(self):
        while True:
            try:
                self.client = paramiko.SSHClient()  # MySSHClient()
                self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.client.connect(hostname=self.ip, port=22, username=self.username, password=self.password,
                                    timeout=self.timeout, allow_agent=False, look_for_keys=False)
                print('连接%s成功' % self.ip)
                return
            except Exception as e1:
                if self.try_times != 0:
                    print('连接%s失败，进行重试' % self.ip)
                    self.try_times -= 1
                else:
                    print('重试3次失败，结束程序')
                    exit(1)

    def close(self):
        self.client.close()

    def exec(self, _cmd, is_show=False):
        print(">>>", _cmd, "<<<")
        res_str = ""
        stdin, stdout, stderr = self.client.exec_command(_cmd, get_pty=True)
        while not stdout.channel.exit_status_ready():
            result = stdout.readline()
            res_str += result
            # print(result.strip())
            if stdout.channel.exit_status_ready():
                break
        res_str = '\n'.join([_l for _l in res_str.split('\n') if _l != ''])  # 去除多余空行
        if is_show:
            print(res_str)
        return res_str

    def file_put(self, local_file, remote_file):
        t = paramiko.Transport(self.ip, 22)
        t.connect(username=self.username, password=self.password)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.put(local_file, remote_file)
        t.close()

    def file_get(self, remote_path, local_path):
        t = paramiko.Transport(self.ip, 22)
        t.connect(username=self.username, password=self.password)
        sftp = paramiko.SFTPClient.from_transport(t)
        local_file_path = os.path.join(local_path, os.path.basename(remote_path))
        sftp.get(remote_path, local_file_path)
        t.close()
        return local_file_path


if __name__ == '__main__':
    # host = '192.168.206.129'
    # username = "root"
    # password = 'qwer2850.'
    # ssh = ConnectSSH(host, username, password)
    # ssh.connect()
    # ssh.file_put("../static/file_save/rpmbuild.tar.gz", "/root/rpmbuild.tar.gz")
    import re
    ssh_ls_str = "/fefa/vim-8.2-620001.src.rpm"
    r = re.search(".*\.src\.rpm", ssh_ls_str)
    print(r.group())


